﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using NRemedy;
using BMC.ARSystem;

namespace Wicresoft.NRemedy.VS10Addin.UI
{
    public class Loader
    {
        public event SendFormListDelegation OnLoadCompeleted;

        private string _server;
        private string _user;
        private string _password;
        private string _namelike;

        public Loader()
        {
        }

        //这个函数在UI线程中执行 
        public void LoadFormList(string server,string user,string password,string namelike)
        {
            _server = server;
            _user = user;
            _password = password;
            _namelike = namelike;
            Thread thread = new Thread(new ThreadStart(LoadInternal));
            thread.Start();
        }
        //这个函数在新的线程中执行 
        private void LoadInternal()
        {
            List<string> rdata = new List<string>();

            try
            {
                using (ARLoginContext context = new ARLoginContext(_server, _user, _password))
                {
                    ARSchema schema = new ARSchema(context);
                    foreach (ARForm f in schema.GetListForm())
                    {
                        rdata.Add(f.Name);
                    }
                }
            }
            catch
            {
                return;
            }

            if (OnLoadCompeleted != null)
            {
                //获取myDelegate的目标对象，这里将是Form1的实例 
                Control control = OnLoadCompeleted.Target as Control;
                //如果目标对象是个Control的话 
                if (control != null)
                {
                    //通过调用form的invoke，把委托指向的函数NotifyReceiver送到UI线程上执行 
                    control.Invoke(OnLoadCompeleted, rdata);
                }
                //如果目标对象不是Control，则直接执行委托 
                else
                {
                    OnLoadCompeleted(rdata);
                }
            } 

        } 
            
    }
}
